package com.example.testdemo.random;

import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;

import com.example.testdemo.R;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * Created by MrYan on 2018/9/4.
 * 求 指定个数 n
 * 指定 min - max 之间的 n 个随机数
 * 其和 = sum
 */

public class RandomActivity extends Activity {
    private static final String TAG = "RandomActivity";
    private int n = 50;
    private int min = 100;
    private int max = 30000;
    private int sum = 100000;
    private Random rand;
    private int number = 0;
    private List<Integer> numList;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_random);
        rand = new Random();
        numList = new ArrayList<>();
    }


    public void evaluation(View view) {
        if (n * min > sum || n * max < sum) {
            throw new IllegalArgumentException("不管怎么求值，都不能符合要求，总和不能小于 n 倍的 min，并且不能大于 n 倍的 max");
        }
        number = 0;
        int num = getARandom();

        while(number < sum){
            if (number < sum){
                if (sum - number < min){
                    Log.d(TAG, "evaluation: sum - number < min 清空");
                    //重来
                    number = 0;
                    numList.clear();
                }else {
                    if (sum - number <= max && numList.size() - 1 == n){
                        num = sum - number;
                        numList.add(num);
                        number = sum;
                    }else {
                        Log.d(TAG, "evaluation: addNum " + num);
                        number = number + num;
                        numList.add(num);
                        num = getARandom();
                    }
                }
            }
            if (number > sum){
                Log.d(TAG, "evaluation: number > sum 清空");
                //重来
                number = 0;
                numList.clear();
            }
            if (number == sum){
                Log.d(TAG, "evaluation: number = " + number);
                if (numList.size() == n) {
                    outPutNumber();
                }else {
                    Log.d(TAG, "evaluation: numList.size() != n 清空:" + numList.size());
                    //重来
                    number = 0;
                    numList.clear();
                }
            }
        }
    }

    private void outPutNumber() {
        for (int i = 0; i < numList.size(); i++) {
            Log.d(TAG, "outPutNumber: " + numList.get(i));
        }
    }


    private int getARandom() {
        return rand.nextInt(max - min + 1) + min;
    }
}
